<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Attachment;
use app\common\model\Collection;
use app\common\model\CollectionJoinContent;
use app\common\model\Content;
use app\common\model\Enterprise;
use app\common\model\InformationQualifications;
use app\common\model\Message;
use app\common\model\OfflineInformation;
use app\common\model\Poster;
use app\common\model\ShowExamine;
use app\common\model\UserCardOrders;
use app\common\model\UserInfo;
use app\common\model\UserQualifications;
use think\Db;
use think\Exception;

class User extends Api
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ['getToken', 'actionGetOtherHome', 'getInformationDetail', 'getMyTrainingCheckIn', 'getCourseList', 'getQualificationsList'];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['*'];

    protected $params = [];

    protected $page = 1;
    protected $pageSize = 10;

    public function __construct()
    {
        parent::__construct();
        $this->params = array_filter(array_merge($this->request->post(), $this->request->get()));
        $this->page = $this->request->param('page', 1);
        $this->pageSize = $this->request->param('pageSize', 10);
    }

    /**
     * 获取测试用户token
     * */
    public function getToken()
    {
        $this->auth->direct($this->params['user_id']);
        $this->success('success', $this->auth->getUserinfo());
    }

    /**
     * 用户设置资料公开
     * */
    public function setOpen()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.setOpen');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (empty($this->params['state'])) {
            $this->error($validate);
        }
        if (!$rows = \app\common\model\User::instance()->get(['id' => $this->auth->id ?? 0])) {
            $this->error('该用户不存在');
        }
        if (!$userInfo = UserInfo::instance()->where(['user_id' => $this->auth->id ?? 0])->order('createtime DESC')->find()) {
            $this->error('请先完善个人基本信息');
        }
        /*if ($userInfo['is_rz'] != 2) {
            $this->error('请先完成您的实名认证');
        }*/
        Db::startTrans();
        try {
            $save['state'] = $this->params['state'];
            if ($this->params['status'] == 1) {
                /*if (ShowExamine::instance()->get(['user_id' => $this->auth->id ?? 0, 'status' => 1, 'type' => 1])) {
                    throw new Exception('您已经提交过了公开申请,请耐心等待平台审核，请勿重复提交');
                }*/
                $new_date = array_merge($userInfo->toArray(), ['status' => $this->params['status']]);
                ShowExamine::instance()->allowField(true)->save(['user_id' => $this->auth->id ?? 0, 'type' => 1, 'orign_data' => json_encode($userInfo, JSON_UNESCAPED_UNICODE), 'new_date' => json_encode($new_date, JSON_UNESCAPED_UNICODE)]);
            } else {
                $save['status'] = 2;
            }
            Db::commit();
            $result = $userInfo->allowField(true)->save($save);
            $this->success('success', $result);
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 设置用户个人信息
     * */
    public function setUserInfo()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.setUserInfo');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!is_float($this->params['price']) && !is_numeric($this->params['price'])) {
            $this->error('请输入正确的课酬');
        }
        Db::startTrans();
        try {
            $this->params['user_id'] = $this->auth->id ?? 0;
            // 保存个人信息
            UserInfo::instance(array_merge($this->params, ['status' => 2]))->submit();
            \app\common\model\User::instance()->allowField(true)->save([
                'avatar' => $this->params['avatar'] ?? '',
                'nickname' => $this->params['nickname'] ?? ''
            ], array_filter(['id' => $this->params['user_id']]));
            // todo 将这些线上的用户的资料更新到资料表的线上用户资料中
            if ($offline = OfflineInformation::instance()->get(['to_user_id' => $this->auth->id ?? 0, 'content_type' => 1])) {
                $offline->allowField(true)->save([
                    'username' => $this->params['nickname'] ?? '',
                    'wxh' => $this->params['wechat_number'] ?? '',
                    'address' => $this->params['city'] ?? '',
                    'sex' => $this->params['sex'] ?? '',
                    'mobile' => $this->params['mobile'] ?? '',
                    'topic' => $this->params['topic'] ?? '',
                    'industry' => $this->params['industry'] ?? '',
                    'file' => $this->params['enclosure'] ?? '',
                    'filename' => $this->params['enclosure_name'] ?? '',
                    'introduce' => $this->params['introduce'] ?? '',
                ]);
            }
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 设置用户资质名称
     * */
    public function setUserQualifications()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.setUserQualifications');
        if ($validate !== true) {
            $this->error($validate);
        }

        Db::startTrans();
        try {
            $this->params['user_id'] = $this->auth->id ?? 0;
            UserQualifications::instance($this->params)->submit();
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 设置用户资质文件
     * */
    public function setUserQualificationsPath()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.setUserQualificationsPath');
        if ($validate !== true) {
            $this->error($validate);
        }

        Db::startTrans();
        try {
            $this->params['user_id'] = $this->auth->id ?? 0;
            if (UserQualifications::instance($this->params)->submit()) {
                Db::commit();
                $this->success('success');
            }
            throw new Exception('保存失败');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取用户设置的资质
     * @throws
     * */
    public function getUserQualifications()
    {
        try {
            $field = 'id, name, path, path_file_names as path_file_name, status';
            $rows = collection(UserQualifications::instance()->field($field)
                ->where(['user_id' => $this->auth->id ?? 0])
                ->select())->toArray();
            foreach ($rows as &$value) {
                $value['is_upload'] = 1;
                if (!empty($value['path'])) {
                    $value['is_upload'] = 2;
                }
            }
            $this->success('success', $rows);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 删除资质证书
     * @throws
     * */
    public function delQualifications()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.delQualifications');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!$rows = UserQualifications::instance()->get(['id' => $this->params['primary_id']])) {
            $this->error('未找到该证书');
        }

        Db::startTrans();
        try {
            $response = $rows->delete();
            Db::commit();
            $this->success('success', $response);
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 删除线下资质证书
     * @throws
     * */
    public function delInformationQualifications()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.delQualifications');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!$rows = InformationQualifications::instance()->get(['id' => $this->params['primary_id']])) {
            $this->error('未找到该证书');
        }

        Db::startTrans();
        try {
            $response = $rows->delete();
            Db::commit();
            $this->success('success', $response);
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取用户设置的个人信息
     * @throws
     * */
    public function getUserInfo()
    {
        try {
            $field = 'createtime, updatetime';
            if (!$rows = UserInfo::instance()->field($field, true)->where(['user_id' => $this->auth->id ?? 0])->find()) {
                $this->error('请完善个人信息', ['status' => 2]);
            }
            $rows['avatar'] = \app\common\model\User::instance()->where(['id' => $this->auth->id ?? 0])->value('avatar') ?? null;
            // 获取该用户的会员
            $condition['user_id'] = $this->auth->id ?? 0;
            $condition['status'] = 2;
            $rows['member_expire_date'] = '';
            $rows['memberAuth'] = '0/0';
            $rows['fileSizeMb'] = config('site.fileSizeMb');
            if ($orders = UserCardOrders::instance()->where($condition)->order('createtime DESC')->find()) {
                $params = json_decode($orders['params'], true);
                $rows['member_expire_date'] = date('Y-m-d', strtotime($orders['expire_date']));
                // todo 会员的名片交换次数
                if (!empty($orders['params'])) {
                    $messageNumber = Message::instance()->where(['user_id|to_user_id' => $this->auth->id ?? 0, 'status' => 2, 'type' => 1])->count(1);
                    $rows['memberAuth'] = $messageNumber . '/' . $params['look_number'] . '次（' . date('Y-m-d', strtotime($orders['pay_time'])) . '-' . date('Y-m-d', strtotime($orders['expire_date'])) . '）';
                    $rows['usedMemberAuth'] = $messageNumber;
                    $rows['totalMemberAuth'] = $params['look_number'];
                }
                $rows['fileSizeMb'] = $params['file_capacity'];
            }
            $attachment = Attachment::where(['user_id' => $this->auth->id ?? 0])->sum('filesize');
            $rows['usedFileSizeMb'] = round($attachment / (1024 * 1024), 2);
            $rows['enclosure_suffix'] = pathinfo($rows['enclosure'], PATHINFO_EXTENSION);
            $rows['myTeacherNumber'] = OfflineInformation::instance()->where(['user_id' => $this->auth->id ?? 0])->count(1);
            $this->success('获取成功', $rows);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-新建详细内容
     * @throws
     * */
    public function addContent()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.addContent');
        if ($validate !== true) {
            $this->error($validate);
        }
        Db::startTrans();
        try {
            $this->params['user_id'] = $this->auth->id ?? 0;
            Content::instance()->allowField(true)->save($this->params);
            $saveAll = [];
            if (!empty($this->params['collection_ids'])) {
                $collection_ids = explode(',', $this->params['collection_ids']);
                // 查询合集是否存在
                if (!$rows = collection(Collection::instance()->where(['id' => ['in', $collection_ids]])->select())->toArray()) {
                    throw new Exception('添加的合集不存在');
                }
                $collection_ids = array_intersect(array_column($rows, 'id'), $collection_ids);
                foreach ($collection_ids as $key => $value) {
                    $saveAll[$key]['collection_id'] = $value;
                    $saveAll[$key]['content_id'] = Content::instance()->id;
                    $saveAll[$key]['user_id'] = $this->params['user_id'];
                }
                CollectionJoinContent::instance()->allowField(true)->saveAll($saveAll, true);
            }
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-查询新建的详细内容
     * @throws
     * */
    public function getContentList()
    {
        try {
            $condition['user_id'] = $this->auth->id ?? 0;
            if (!empty($this->params['searchName'])) {
                $condition['title'] = ['LIKE', '%' . $this->params['searchName'] . '%'];
            }
            $order = 'createtime asc';
            if (!empty($this->params['time_sort'])) {
                $order = 'createtime ' . $this->params['time_sort'];
            }
            if (!empty($this->params['file_filter'])) {
                $condition['file'] = ($this->params['file_filter'] == 1) ? ['<>', ''] : null;
            }
            $list = Content::instance()
                ->field('id, title, content, file, status, createtime')
                ->where($condition)
                ->order($order)
                ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) {
                    $value['fileSuffix'] = '';
                    if (!empty($value['file'])) {
                        $value['fileSuffix'] = pathinfo($value['file'], PATHINFO_EXTENSION);
                    }
                });
            $this->success('success', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-修改列表权限是否公开
     * @throws
     * */
    public function updateAuthStatus()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.updateAuthStatus');
        if ($validate !== true) {
            $this->error($validate);
        }
        Db::startTrans();
        try {
            $content = collection(Content::instance()->where(['id' => ['in', array_unique(explode(',', $this->params['content_ids']))]])->select())->toArray();
            $oldArray = [];
            foreach ($content as $contentKey => $contentValue) {
                $oldArray[$contentKey]['id'] = $contentValue['id'];
                $oldArray[$contentKey]['status'] = $contentValue['status'];
            }
            $array = [];
            foreach (explode(',', $this->params['content_ids']) as $key => $value) {
                $array[$key]['id'] = $value;
                $array[$key]['status'] = $this->params['status'];
            }
            $new_date = $array;
            ShowExamine::instance()->allowField(true)->save(['user_id' => $this->auth->id ?? 0, 'type' => 2, 'orign_data' => json_encode($oldArray, JSON_UNESCAPED_UNICODE), 'new_date' => json_encode($new_date, JSON_UNESCAPED_UNICODE)]);
            /*Content::instance()->allowField(true)->saveAll($array, true);*/
            Db::commit();
            $this->success('操作成功,请等待审核');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

    }

    /**
     * 我的内容-列表内容删除
     * @throws
     * */
    public function delContent()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.delContent');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!$rows = Content::instance()->get(['id' => $this->params['primary_id']])) {
            $this->error('该数据不存在');
        }
        Db::startTrans();
        try {
            $rows->delete();
            CollectionJoinContent::instance()->where(['content_id' => $rows['id']])->delete();
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-列表内容重命名
     * @throws
     * */
    public function updateContentName()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.updateContentName');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!$rows = Content::instance()->get(['id' => $this->params['primary_id']])) {
            $this->error('该数据不存在');
        }
        Db::startTrans();
        try {
            $rows->allowField(true)->save(['title' => $this->params['title']]);
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-列表内容加入合集
     * @throws
     * */
    public function joinCollection()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.joinCollection');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!$rows = Content::instance()->get(['id' => $this->params['primary_id']])) {
            $this->error('要加入合集的数据不存在');
        }
        $collection_ids = explode(',', $this->params['collection_ids']);
        if (!$result = collection(Collection::instance()->where(['id' => ['in', $collection_ids]])->select())->toArray()) {
            $this->error('要加入的合集不存在');
        }
        $collection_ids = array_unique(array_intersect($collection_ids, array_column($result, 'id')));
        Db::startTrans();
        try {
            $save = [];
            foreach ($collection_ids as $key => $value) {
                $save[$key]['collection_id'] = $value;
                $save[$key]['content_id'] = $this->params['primary_id'];
                $save[$key]['user_id'] = $this->auth->id ?? 0;
            }
            // 删除加入的旧的合集
            CollectionJoinContent::instance()->where(['content_id' => ['in', $this->params['primary_id']], 'user_id' => $this->auth->id ?? 0])->delete();
            // 加入新的合集
            CollectionJoinContent::instance()->allowField(true)->saveAll($save, true);
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-新增批量上传文件的数据
     * @throws
     * */
    public function uploadContentFile()
    {
        $size = 10 * 1024 * 1024;
        $mimetype = config('upload.mimetype');
        $ext = explode(',', $mimetype);
        $user_id = $this->auth->id ?? 0;
        Db::startTrans();
        try {
            $file = $this->request->file('file');
            if (!$file) {
                throw new Exception('请上传文件');
            }
            $array = [];
            $attachment = [];
            foreach ($file as $key => $files) {
                $extension = pathinfo($files->getInfo()['name'], PATHINFO_EXTENSION);
                if (!in_array($extension, $ext)) {
                    throw new Exception('请上传文件后缀为【$mimetype】的文件');
                }
                $tmp_name = $files->getInfo()['tmp_name'];
                $sha1 = hash_file('sha1', $tmp_name);
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $files->validate(['size' => $size, 'ext' => $mimetype])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . date('Ymd') . '_' . $user_id, false, true);
                list($fileName, $sub) = explode('.', $info->getSaveName());
                $array[$key]['title'] = $fileName;
                $array[$key]['user_id'] = $user_id;
                $array[$key]['file'] = DS . 'uploads' . DS . date('Ymd') . '_' . $user_id . DS . $info->getSaveName();
                // todo 附件数组
                $suffix = strtolower(pathinfo($files->getInfo()['name'], PATHINFO_EXTENSION));
                $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
                $attachment[$key]['user_id'] = $this->auth->id ?? 0;
                $attachment[$key]['filename'] = $fileName;
                $attachment[$key]['filesize'] = $files->getInfo()['size'];
                if (in_array($files->getInfo()['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
                    $imgInfo = getimagesize($files->getInfo()['tmp_name']);
                    if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
                        throw new UploadException(__('Uploaded file is not a valid image'));
                    }
                    $attachment[$key]['imagewidth'] = $imgInfo[0] ?? 0;
                    $attachment[$key]['imageheight'] = $imgInfo[1] ?? 0;
                }
                $attachment[$key]['imagetype'] = $suffix;
                $attachment[$key]['mimetype'] = $files->getInfo()['type'];
                $attachment[$key]['url'] = $array[$key]['file'];
                $attachment[$key]['uploadtime'] = time();
                $attachment[$key]['storage'] = 'local';
                $attachment[$key]['sha1'] = $sha1;
                $attachment[$key]['extparam'] = '';
            }
            Content::instance()->allowField(true)->saveAll($array);
            // 写入附件表
            (new Attachment())->allowField(true)->saveAll($attachment, true);
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-新增批量上传文件的数据（新版）
     * @throws
     * */
    public function uploadContentFileV2()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.uploadContentFileV2');
        if ($validate !== true) {
            $this->error($validate);
        }

        Db::startTrans();
        try {
            $fileParams = htmlspecialchars_decode($this->params['fileParams']);
            $fileParams = json_decode($fileParams, true);
            $array = [];
            foreach ($fileParams as $key => $files) {
                $array[$key]['title'] = $files['title'];
                $array[$key]['user_id'] = $this->auth->id ?? 0;
                $array[$key]['file'] = $files['file'];
            }
            Content::instance()->allowField(true)->saveAll($array);
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-合集列表获取
     * */
    public function getCollectionList()
    {
        try {
            $condition['t1.user_id'] = $this->auth->id ?? 0;
            if (!empty($this->params['searchName'])) {
                $condition['t1.title'] = ['LIKE', '%' . $this->params['searchName'] . '%'];
            }
            $fileWhere = [];
            if (!empty($this->params['file_filter'])) {
                $fileWhere['t3.file'] = ($this->params['file_filter'] == 1) ? ['<>', ''] : null;
            }
            $order = 't1.createtime asc';
            if (!empty($this->params['time_sort'])) {
                $order = 't1.createtime ' . $this->params['time_sort'];
            }
            $list = Collection::instance()
                ->alias('t1')
                ->field('t1.id, t1.title')
                ->with(['innerCollectionJoinContentHasMany'])
                ->join('collection_join_content t2', 't1.id = t2.collection_id', 'LEFT')
                ->join('content t3', 't2.content_id = t3.id', 'LEFT')
                ->where($condition)
                ->where($fileWhere)
                ->group('t1.id')
                ->order($order)
                ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) {
                    $list = collection($value['inner_collection_join_content_has_many'])->toArray();
                    foreach ($list as &$item) {
                        $item['extension'] = pathinfo($item['file'], PATHINFO_EXTENSION);
                    }
                    $value['list'] = $list;
                    unset($value['inner_collection_join_content_has_many']);
                });
            $this->success('success', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-创建合集
     * @throws
     * */
    public function createCollection()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.createCollection');
        if ($validate !== true) {
            $this->error($validate);
        }
        if ($rows = Collection::instance()->where(['title' => $this->params['title']])->find()) {
            $this->error('该名称已存在');
        }
        Db::startTrans();
        try {
            Collection::instance()->allowField(true)->save([
                'title' => $this->params['title'],
                'user_id' => $this->auth->id ?? 0
            ]);
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-删除合集
     * @throws
     * */
    public function delCollection()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.delCollection');
        if ($validate !== true) {
            $this->error($validate);
        }
        $ids = Collection::instance()->where(['id' => ['in', explode(',', $this->params['collection_ids'])]])->column('id');
        if (!$ids) {
            $this->error('需要删除的合集不存在');
        }
        Db::startTrans();
        try {
            Collection::instance()->where(['id' => ['in', $ids]])->delete();
            CollectionJoinContent::instance()->where(['collection_id' => ['in', $ids]])->delete();
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-修改合集名称
     * @throws
     * */
    public function updateCollectionName()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.updateCollectionName');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!$rows = Collection::instance()->get(['id' => $this->params['primary_id']])) {
            $this->error('该数据不存在');
        }
        Db::startTrans();
        try {
            $rows->allowField(true)->save(['title' => $this->params['title']]);
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-获取合集下的内容列表
     * @throws
     * */
    public function getCollectionContent()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.getCollectionContent');
        if ($validate !== true) {
            $this->error($validate);
        }
        try {
            $condition['collection_id'] = $this->params['primary_id'];
            if (!empty($this->params['searchName'])) {
                $condition['title'] = ['LIKE', '%' . $this->params['searchName'] . '%'];
            }
            $list = CollectionJoinContent::instance()
                ->field('content_id')
                ->with(['innerJoinContentHasOne'])
                ->where($condition)
                ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) {
                    $value['extension'] = pathinfo($value['file'], PATHINFO_EXTENSION);
                    unset($value['inner_join_content_has_one']);
                });
            $this->success('success', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-合集下的内容列表删除
     * @throws
     * */
    public function delCollectionContent()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.delCollectionContent');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!$rows = Collection::instance()->get(['id' => $this->params['primary_id']])) {
            $this->error('该数据不存在');
        }
        $content_ids = explode(',', $this->params['content_ids']);
        Db::startTrans();
        try {
            CollectionJoinContent::instance()->where(['content_id' => ['in', $content_ids], 'collection_id' => $this->params['primary_id'], 'user_id' => $this->auth->id ?? 0])->delete();
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的内容-合集下添加内容
     * @throws
     * */
    public function collectionAddContent()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.collectionAddContent');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!$rows = Collection::instance()->get(['id' => $this->params['primary_id']])) {
            $this->error('该数据不存在');
        }

        Db::startTrans();
        try {
            $content_ids = explode(',', $this->params['content_ids']);
            // todo 先删除旧的
            CollectionJoinContent::instance()->where(['content_id' => ['in', $content_ids]])
                ->where(['collection_id' => $this->params['primary_id'], 'user_id' => $this->auth->id ?? 0])
                ->delete();
            // todo 添加新的合集内容
            $array = [];
            foreach ($content_ids as $key => $value) {
                $array[$key]['content_id'] = $value;
                $array[$key]['collection_id'] = $this->params['primary_id'];
                $array[$key]['user_id'] = $this->auth->id ?? 0;
            }
            CollectionJoinContent::instance()->allowField(true)->saveAll($array, true);
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取当前登录用户的公开内容
     * */
    public function getUserPublicContent()
    {
        try {
            $field = 'id, title, content, file, status';
            $list = collection(Content::instance()->field($field)->where(['user_id' => $this->auth->id ?? 0])->select())->toArray();
            foreach ($list as $key => &$value) {
                $value['extension'] = pathinfo($value['file'], PATHINFO_EXTENSION);
            }
            $this->success('success', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 用户主页搜索资质和内容
     * */
    public function userHomeSearch()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.userHomeSearch');
        if ($validate !== true) {
            $this->error($validate);
        }
        if ($this->params['tabType'] == 1) {
            $model = Content::instance();
        } else {
            $model = UserQualifications::instance();
        }
        try {
            $condition['user_id'] = $this->auth->id ?? 0;
            if (!empty($this->params['searchName'])) {
                $keyName = ($this->params['tabType'] == 1) ? 'title' : 'name';
                $condition[$keyName] = ['LIKE', '%' . $this->params['searchName'] . '%'];
            }
            $list = collection($model->where($condition)->select())->toArray();
            $this->success('success', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 培训打卡
     * */
    public function trainingCheckIn()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.trainingCheckIn');
        if ($validate !== true) {
            $this->error($validate);
        }
        Db::startTrans();
        try {
            $requestUrl = http_query_url('https://qifu-api.baidubce.com/ip/geo/v1/district?ip=' . $this->request->ip());
            if ($requestUrl && $requestUrl['code'] == 'Success' && !empty($requestUrl['data'])) {
                $prov = empty($requestUrl['data']['prov']) ? '' : $requestUrl['data']['prov'];
                $city = empty($requestUrl['data']['city']) ? '' : $requestUrl['data']['city'];
                if ($prov && $city) {
                    $this->params['city'] = $prov . '.' . $city;
                }
            }
            $this->params['user_id'] = $this->auth->id ?? 0;
            $response = Poster::instance()->allowField(true)->save($this->params);
            if ($response) {
                Db::commit();
                $this->success('success', ['id' => Poster::instance()->id]);
            }
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取培训打卡并生成海报
     * */
    public function getTrainingCheckInPoster()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.getTrainingCheckInPoster');
        if ($validate !== true) {
            $this->error($validate);
        }

        try {
            if (!$rows = Poster::instance()->get(['id' => $this->params['primary_id']])) {
                throw new Exception('未查询到培训打卡数据');
            }
            $rows = $rows->toArray();
            // todo 获取accessToken
            $applicationConfig = ['grant_type' => 'client_credential', 'appid' => config('site.appid'), 'secret' => config('site.secret')];
            $accessToken = http_query_url('https://api.weixin.qq.com/cgi-bin/token', 'get', $applicationConfig);
            // todo 获取小程序码
            $qrCodeConfig = json_encode(array(
                'scene' => 'user_id:' . $this->auth->id ?? 0,
                'page' => config('site.pageUrl'),
                'check_path' => false
            ), JSON_UNESCAPED_UNICODE);
            $result = http_query_url('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $accessToken['access_token'], 'post', $qrCodeConfig, [
                'Content-Type: application/json; charset=utf-8',
                'Content-Length:' . strlen($qrCodeConfig),
                'Cache-Control: no-cache',
                'Pragma: no-cache'
            ], true);
            // 将二维码的文件流写入到图片中
            $commonPath = DS . 'uploads' . DS . 'qr_code' . DS . date('Ymd') . '_' . $this->auth->id ?? 0;
            $pathDir = ROOT_PATH . 'public' . $commonPath;
            if (!is_dir($pathDir)) {
                mkdir($pathDir, 0777, true);
            }
            $fileName = date('Ymd') . '.png';
            if (!file_exists($pathDir . DS . $fileName)) {
                touch($pathDir . DS . $fileName);
            }
            // 将文件流写入到图片
            file_put_contents($pathDir . DS . $fileName, $result);
            $rows['qrCodePath'] = $commonPath . DS . $fileName;
            $this->success('success', $rows);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的人脉-新建他人线下资料
     * */
    public function addNewOtherInformation()
    {
        $model = new OfflineInformation();
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.addNewOtherInformation');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!empty($this->params['price'])) {
            if (!is_float($this->params['price']) && !is_numeric($this->params['price'])) {
                $this->error('请输入正确的课酬');
            }
        }

        if (empty($this->params['is_type'])) {
            $this->error('缺少绑定类型');
        }
        if ($this->params['is_type'] == 1) {
            unset($this->params['to_user_id']);
        }
        // 避免重复添加
        if (!empty($this->params['id_card'])) {
            if ($model::instance()->get(['id_card' => $this->params['id_card'], 'user_id' => ['<>', $this->auth->id ?? 0], 'content_type' => 2])) {
                $this->error('该用户已存在');
            }
        }
        if (!empty($this->params['mobile'])) {
            if ($model::instance()->get(['mobile' => $this->params['mobile'], 'user_id' => ['<>', $this->auth->id ?? 0], 'content_type' => 2])) {
                $this->error('该手机号已存在');
            }
        }
        if (!empty($this->params['opening_bank']) && !empty($this->params['bank_card'])) {
            if ($model::instance()->get(['opening_bank' => $this->params['opening_bank'], 'bank_card' => $this->params['bank_card'], 'user_id' => ['<>', $this->auth->id ?? 0], 'content_type' => 2])) {
                $this->error('该卡号已存在');
            }
        }
        if ($this->params['is_type'] == 2) {
            if ($model::get(['user_id' => $this->auth->id ?? 0, 'to_user_id' => $this->params['to_user_id']])) {
                $this->error('您们已是绑定关系,请勿重复绑定');
            }

            if ($this->auth->id == $this->params['to_user_id']) {
                $this->error('请勿自己绑定自己');
            }
        } else {
            unset($this->params['to_user_id']);
        }
        $primaryID = [];
        if (!empty($this->params['id'])) {
            if (!$model::instance()->get(['id' => $this->params['id']])) {
                $this->error('编辑的资料不存在');
            }
            $primaryID['id'] = $this->params['id'];
            $this->params['updatetime'] = date('Y-m-d H:i:s');
        }
        $qualifications = [];
        if (!empty($this->params['qualifications'])) {
            $qualifications = json_decode(htmlspecialchars_decode($this->params['qualifications']), true);
        }
        unset($this->params['id']);
        Db::startTrans();
        try {
            $this->params['user_id'] = $this->auth->id ?? 0;
            $this->params['state'] = 2;
            $this->params['type'] = 3;
            $this->params['content_type'] = 2;
            $response = $model::instance()->allowField(true)->save($this->params, array_filter($primaryID));
            if ($qualifications) {
                $qualificationsArray = [];
                $oid = empty(array_filter($primaryID)) ? $model::instance()->id : $primaryID['id'];
                foreach ($qualifications as $qualificationsKey => $qualificationsValue) {
                    $qualificationsArray[$qualificationsKey] = $qualificationsValue;
                    $qualificationsArray[$qualificationsKey]['oid'] = $oid;
                }
                // todo 先删除该线下资料的资质
                InformationQualifications::instance()->where(['oid' => $oid])->delete();
                // todo 重新新增线下资料最新的资质
                InformationQualifications::instance()->allowField(true)->saveAll($qualificationsArray);
            }
            if ($response) {
                Db::commit();
                $this->success('success', $response);
            }
            throw new Exception('保存失败');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的人脉-解绑人脉
     * @throws
     * */
    public function unbindPersonal()
    {
        if (empty($this->params['to_user_id'])) {
            $this->error('缺少需要解绑的用户ID');
        }
        if (!\app\common\model\User::instance()->get(['id' => $this->params['to_user_id']])) {
            $this->error('未找到需要解绑的用户信息');
        }
        if (!$offline = OfflineInformation::instance()->get(['to_user_id' => $this->params['to_user_id'], 'user_id' => $this->auth->id ?? 0])) {
            $this->error('该用户和您不是绑定关系');
        }
        Db::startTrans();
        try {
            if ($user = OfflineInformation::instance()->where(['id' => $offline['id']])->delete()) {
                Db::commit();
                $this->success('解绑成功');
            }
            throw new Exception('解绑失败');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 人脉关联-查询点击微信邀请链接进入关联的用户是否已被关联
     * @throws
     * */
    public function checkJoin()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.joinSuccessOrFail');
        if ($validate !== true) {
            $this->error($validate);
        }

        if (!$user = \app\common\model\User::instance()->get(['id' => $this->params['user_id']])) {
            $this->error('分享邀请的用户不存在');
        }
        /*if (!$userInfo = UserInfo::instance()->get(['user_id' => $this->auth->id ?? 0])) {
            $this->error('请先完善您的个人资料');
        }
        if ($userInfo['is_rz'] != 2) {
            $this->error('请先完成您的实名认证');
        }*/
        // todo 避免自己绑定自己
        if ($this->auth->id == $this->params['user_id']) {
            $this->error('无法自己与自己进行人脉关系绑定');
        }
        $queryWhere['user_id'] = $this->params['user_id'];
        $queryWhere['to_user_id'] = $this->auth->id ?? 0;
        $queryWhere['state'] = 2;
        $rows = OfflineInformation::instance()->get($queryWhere);
        if ($rows) {
            $this->error('该用户与您已经绑定过人脉关系了');
        }
        $this->success('success');
    }

    /**
     * 查询我与他人是否绑定关系
     * @throws
     * */
    public function checkMyJoinOther()
    {
        if (empty($this->params['other_uid'])) {
            $this->error('缺少检测被绑定人的用户ID');
        }
        if (!$user = \app\common\model\User::instance()->get(['id' => $this->params['other_uid']])) {
            $this->error('查询用户不存在');
        }
        $bindOne = OfflineInformation::instance()
            ->where(['state' => 2])
            ->where(['user_id' => $this->auth->id ?? 0, 'to_user_id' => $this->params['other_uid']])
            ->count(1);
        $bindTwo = OfflineInformation::instance()
            ->where(['state' => 2])
            ->where(['user_id' => $this->params['other_uid'], 'to_user_id' => $this->auth->id ?? 0])
            ->count(1);
        $is_bind = false;
        if ($bindOne) {
            $is_bind = true;
        }
        if ($bindTwo) {
            $is_bind = true;
        }
        $this->success('success', ['is_bind' => $is_bind]);
    }

    /**
     * 人脉关联-被邀请者同意完成关联
     * @throws
     * */
    public function joinSuccessOrFail()
    {
        $offlineInformation = new OfflineInformation();
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.joinSuccessOrFail');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (empty($this->params['type'])) {
            $this->error('缺少关联类型');
        }
        if (empty($this->params['content_type'])) {
            $this->error('缺少内容类型');
        }
        if (!$user = \app\common\model\User::instance()->get(['id' => $this->params['user_id']])) {
            $this->error('分享邀请的用户不存在');
        }
        $userInfo = UserInfo::instance()->get(['user_id' => $this->auth->id ?? 0]);
        /*if (!$userInfo = UserInfo::instance()->get(['user_id' => $this->auth->id ?? 0])) {
            $this->error('请先完善您的个人资料');
        }
        if ($userInfo['is_rz'] != 2) {
            $this->error('请先完成您的实名认证');
        }*/
        // todo 避免自己绑定自己
        if ($this->auth->id == $this->params['user_id']) {
            $this->error('无法自己与自己进行人脉关系绑定');
        }
        // todo 查询当前人脉是否已被当前邀请者关联
        $queryWhere['user_id'] = $this->params['user_id'];
        $queryWhere['to_user_id'] = $this->auth->id ?? 0;
        $queryWhere['state'] = 2;
        if ($this->params['type'] == 2) {
            $queryWhere['pid'] = $this->params['pid'];
        }
        $rows = $offlineInformation::instance()->get($queryWhere);
        if ($rows) {
            $this->error('该用户与您已经绑定过人脉关系了');
        }
        Db::startTrans();
        try {
            // todo 被邀请者用户信息
            if ($userInfo) {
                $field = array_intersect($offlineInformation->getTableFields(), $userInfo->getTableFields());
                $newField = [];
                foreach ($field as $fieldValue) {
                    $newField[$fieldValue] = $userInfo[$fieldValue];
                }
                $field = $offlineInformation::instance()->_initialize($newField)->delField('id, status, user_id, createtime, updatetime');
                $field['username'] = $userInfo['nickname'] ?? '';
                $field['wxh'] = $userInfo['wechat_number'] ?? '';
                $field['address'] = $userInfo['city'] ?? '';
            }
            $field['user_id'] = $this->params['user_id'];
            $field['to_user_id'] = $this->auth->id ?? 0;
            $field['state'] = 2;
            $field['type'] = $this->params['type'];
//            $field['content_type'] = $this->params['content_type'];
            if ($this->params['type'] == 2) {
                $field['pid'] = $this->params['pid'];
            }
            // todo 邀请者用过户信息
            if ($toUserInfo = UserInfo::instance()->get(['user_id' => $this->params['user_id']])) {
                $toField = array_intersect($offlineInformation->getTableFields(), $toUserInfo->getTableFields());
                $toNewField = [];
                foreach ($toField as $toFieldValue) {
                    $toNewField[$toFieldValue] = $toUserInfo[$toFieldValue];
                }
                $toField = $offlineInformation::instance()->_initialize($toNewField)->delField('id, status, user_id, createtime, updatetime');
                $toField['username'] = $toUserInfo['nickname'] ?? '';
                $toField['wxh'] = $toUserInfo['wechat_number'] ?? '';
                $toField['address'] = $toUserInfo['city'] ?? '';
            }
            $toField['user_id'] = $this->auth->id ?? 0;
            $toField['to_user_id'] = $this->params['user_id'];
            $toField['state'] = 2;
            $toField['type'] = $this->params['type'];
//            $toField['content_type'] = $this->params['content_type'];
            if ($this->params['type'] == 2) {
                $toField['pid'] = $this->params['pid'];
            }
            $res = count($offlineInformation::instance()->getSaveAllPk($offlineInformation::instance()->allowField(true)->saveAll(array_merge([$field], [$toField]))));
            if ($res) {
                Db::commit();
                $this->success('绑定关系成功');
            }
            throw new Exception('绑定关系失败');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的人脉-导入新建他人线下资料
     * @throws
     * */
    public function importOtherInformation()
    {
        ini_set("memory_limit", "-1");
        gc_collect_cycles();
        $file = $this->request->file('file');
        if (!$file) {
            $this->error('请上传导入模板');
        }
        $upload = new Upload($file);
        $attachment = $upload->upload();
        $data = $this->readFile($attachment->url);
        if (!$data) {
            $this->error('请在excel内写入数据');
        }
        Db::startTrans();
        try {
            $array = array();
            foreach ($data as $key => $value) {
                $value = array_values($value);
                $array[$key]['username'] = $value[0] ?? '';
                $array[$key]['sex'] = $value[1] ?? 1;
                $array[$key]['mobile'] = $value[2] ?? '';
                $array[$key]['wxh'] = $value[3] ?? '';
                $array[$key]['address'] = $value[4] ?? '';
                $array[$key]['id_card'] = $value[5] ?? '';
                $array[$key]['opening_bank'] = $value[6] ?? '';
                $array[$key]['bank_card'] = $value[7] ?? '';
                $array[$key]['price'] = $value[8] ?? 0;
                $array[$key]['topic'] = $value[9] ?? 0;
                $array[$key]['industry'] = $value[10] ?? 0;
                $array[$key]['note'] = $value[11] ?? 0;
                $array[$key]['introduce'] = $value[12] ?? 0;
                $array[$key]['status'] = $value[13] ?? 1;
                $array[$key]['user_id'] = $this->auth->id ?? 0;
            }
            OfflineInformation::instance()->allowField(true)->saveAll($array, true);
            Db::commit();
            $this->success('上传解析成功', $array);
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 我的人脉-导入新建他人线下资料模板下载
     * @throws
     * */
    public function actionDownTemplate()
    {
        try {
            $this->success('success', array('url' => $this->request->domain() . DS . 'excelTemplate' . DS . '人脉资料表.xlsx'));
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取我的人脉列表
     * */
    public function getMyTrainingCheckIn()
    {
        try {
            if (empty($this->params['type'])) {
                throw new  Exception('缺少获取老师类型');
            }
            if ($this->params['type'] == 1) { // 平台
                $list = UserInfo::instance()->getPlatformTeacher($this->params, $this->auth->id ?? 0, $this->page, $this->pageSize);
            } else { // 我的
                $list = OfflineInformation::instance()->getMyTeacher($this->params, $this->auth->id ?? 0, $this->page, $this->pageSize);
            }
            $this->success('success', $list);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 平台老师-课程列表
     * @throws
     * */
    public function getCourseList()
    {
        $condition['t1.status'] = 2;
        /*$condition['t1.user_id'] = ['<>', $this->auth->id];*/
        if (!empty($this->params['searchName'])) {
            $condition['t1.title|t1.content'] = ['LIKE', '%' . $this->params['searchName'] . '%'];
        }
        $joinSql = '';
        if (!empty($this->params['channel'])) {
            if ($this->params['channel'] == 1) { // 公共人脉
                $condition['t3.id'] = null;
                $condition['t4.id'] = null;
            }

            if ($this->params['channel'] == 2) { // 我的人脉
                $condition['t3.id'] = ['<>', 0];
                $joinSql = ' AND t3.user_id = ' . $this->auth->id ?? 0;
            }

            if ($this->params['channel'] == 3) { // 渠道人脉
                $condition['t4.id'] = ['<>', 0];
            }
        }
        if (!empty($this->params['fileFilter'])) {
            $condition['t1.file'] = ($this->params['fileFilter'] == 1) ? ['<>', ''] : '';
        }
        if (!empty($this->params['address'])) {
            $condition['t2.city'] = ['LIKE', '%' . $this->params['address'] . '%'];
        }
        if (!empty($this->params['industry'])) {
            $condition['t2.industry'] = ['LIKE', '%' . $this->params['industry'] . '%'];
        }
        if (!empty($this->params['topic'])) {
            $condition['t2.topic'] = ['LIKE', '%' . $this->params['topic'] . '%'];
        }
        $orderSort = array();
        if (!empty($this->params['orderSort'])) {
            $order = ($this->params['orderSort'] == 'asc') ? 't1.createtime ASC' : 't1.createtime DESC';
            array_push($orderSort, $order);
        }
        if (!empty($this->params['priceSort'])) {
            $order = ($this->params['priceSort'] == 'asc') ? 't3.price ASC' : 't3.price DESC';
            array_push($orderSort, $order);
        }
        uksort($orderSort, function ($a, $b) {
            // 将键转换为整数并进行比较
            if ($a == $b) {
                return 0;
            }
            return ($a > $b) ? -1 : 1; // 注意这里的负号，因为我们想要降序排序
        });
        $orderSort = implode(',', $orderSort);
        $list = Content::instance()
            ->alias('t1')
            ->field('t1.id, t1.user_id, t1.title, t1.content, t2.is_rz, t2.name, t2.mobile, t2.wechat_number, t1.status, t2.city, t2.identity')
            ->field('t2.topic, t2.industry, t3.price, t3.id as o_id, t3.state as o_state, t3.user_id as bind_uid, t4.id as m_id')
            ->join('user_info t2', 't1.user_id = t2.user_id', 'LEFT')
            ->join('offline_information t3', 't1.user_id = t3.to_user_id' . $joinSql, 'LEFT')
            ->join('message t4', 't1.user_id = t4.to_user_id', 'LEFT')
            ->where($condition)
            ->order($orderSort)
            ->group('t1.id')
            ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) {
                $value['price'] = empty($value['price']) ? 0 : $value['price'];
                $value['city'] = empty($value['city']) ? '' : implode('', explode(',', $value['city']));
                $value['topic'] = empty($value['topic']) ? '' : explode(',', $value['topic']);
                $value['industry'] = empty($value['industry']) ? '' : explode(',', $value['industry']);
                // todo 人脉来源
                $value['source'] = '公共人脉';
                $value['is_rm'] = false;
                $value['is_yq'] = 0;
                if ($message = Message::instance()->where(['user_id' => $this->auth->id ?? 0, 'to_user_id' => $value['user_id'], 'type' => ['in', [1, 2]]])->order('createtime desc')->find()) {
                    $value['source'] = '渠道人脉';
                    $value['is_rm'] = true;
                    $value['is_yq'] = $message['status'];
                }
                if (!empty($value['o_id']) && in_array($value['o_state'], [1, 2]) && ($value['bind_uid'] == $this->auth->id ?? 0)) {
                    $value['source'] = '我的人脉';
                    $value['is_rm'] = true;
                }
                if (!empty($this->params['searchName'])) {
                    // 使用 preg_replace 高亮关键词
                    $value['highlightedName'] = preg_replace(
                        '/(' . preg_quote($this->params['searchName'], '/') . ')/i',
                        '<span class="highlight">$1</span>',
                        $value['title']
                    );
                }
            });
        $this->success('success', $list);
    }

    /**
     * 平台老师-课程列表-进入课程详情
     * @throws
     * */
    public function getCourseDetail()
    {
        if (empty($this->params['id'])) {
            $this->error('缺少课程ID');
        }
        if (!$content = Content::instance()->get(['id' => $this->params['id']])) {
            $this->error('课程不存在');
        }
        $this->success('success', $content);
    }

    /**
     * 平台老师-资质列表
     * @throws
     * */
    public function getQualificationsList()
    {
        $condition['t1.status'] = 2;
        /*$condition['t1.user_id'] = ['<>', $this->auth->id ?? 0];*/
        if (!empty($this->params['searchName'])) {
            $condition['t1.name'] = ['LIKE', '%' . $this->params['searchName'] . '%'];
        }
        $joinSql = '';
        if (!empty($this->params['channel'])) {
            if ($this->params['channel'] == 1) { // 公共人脉
                $condition['t3.id'] = null;
                $condition['t4.id'] = null;
            }

            if ($this->params['channel'] == 2) { // 我的人脉
                $condition['t3.id'] = ['<>', 0];
                $joinSql = ' AND t3.user_id = ' . $this->auth->id ?? 0;
            }

            if ($this->params['channel'] == 3) { // 渠道人脉
                $condition['t4.id'] = ['<>', 0];
            }
        }
        if (!empty($this->params['fileFilter'])) {
            $condition['t1.path'] = ($this->params['fileFilter'] == 1) ? ['<>', ''] : null;
        }
        if (!empty($this->params['address'])) {
            $condition['t2.city'] = ['LIKE', '%' . $this->params['address'] . '%'];
        }
        if (!empty($this->params['industry'])) {
            $condition['t2.industry'] = ['LIKE', '%' . $this->params['industry'] . '%'];
        }
        if (!empty($this->params['topic'])) {
            $condition['t2.topic'] = ['LIKE', '%' . $this->params['topic'] . '%'];
        }
        $orderSort = array();
        if (!empty($this->params['orderSort'])) {
            $order = ($this->params['orderSort'] == 'asc') ? 't1.createtime ASC' : 't1.createtime DESC';
            array_push($orderSort, $order);
        }
        if (!empty($this->params['priceSort'])) {
            $order = ($this->params['priceSort'] == 'asc') ? 't3.price ASC' : 't3.price DESC';
            array_push($orderSort, $order);
        }
        uksort($orderSort, function ($a, $b) {
            // 将键转换为整数并进行比较
            if ($a == $b) {
                return 0;
            }
            return ($a > $b) ? -1 : 1; // 注意这里的负号，因为我们想要降序排序
        });
        $orderSort = implode(',', $orderSort);
        $list = UserQualifications::instance()
            ->alias('t1')
            ->field('t1.id, t1.user_id, t1.name as title, t1.path, t1.status, t2.is_rz, t2.name, t2.nickname, t2.mobile, t2.wechat_number, t2.city, t2.identity')
            ->field('t2.topic, t2.industry, IF(t3.price > 0, t3.price, t2.price) as price')
            ->field('t3.id as o_id, t3.state as o_state, t3.user_id as bind_uid, t4.id as m_id')
            ->join('user_info t2', 't1.user_id = t2.user_id', 'LEFT')
            ->join('offline_information t3', 't1.user_id = t3.to_user_id' . $joinSql, 'LEFT')
            ->join('message t4', 't1.user_id = t4.to_user_id', 'LEFT')
            ->where($condition)
            ->order($orderSort)
            ->group('t1.id')
            ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) {
                $value['name'] = ($value['is_rz'] == 2) ? $value['name'] : $value['nickname'];
                $value['price'] = empty($value['price']) ? 0 : $value['price'];
                $value['city'] = empty($value['city']) ? '' : implode('', explode(',', $value['city']));
                $value['topic'] = empty($value['topic']) ? '' : explode(',', $value['topic']);
                $value['industry'] = empty($value['industry']) ? '' : explode(',', $value['industry']);
                // todo 人脉来源
                $value['source'] = '公共人脉';
                $value['is_rm'] = false;
                $value['is_yq'] = 0;
                if ($message = Message::instance()->where(['user_id' => $this->auth->id ?? 0, 'to_user_id' => $value['user_id'], 'type' => ['in', [1, 2]]])->order('createtime desc')->find()) {
                    $value['source'] = '渠道人脉';
                    $value['is_rm'] = true;
                    $value['is_yq'] = $message['status'];
                }
                if (!empty($value['o_id']) && in_array($value['o_state'], [1, 2]) && ($value['bind_uid'] == $this->auth->id ?? 0)) {
                    $value['source'] = '我的人脉';
                    $value['is_rm'] = true;
                }
                if (!empty($this->params['searchName'])) {
                    // 使用 preg_replace 高亮关键词
                    $value['highlightedName'] = preg_replace(
                        '/(' . preg_quote($this->params['searchName'], '/') . ')/i',
                        '<span class="highlight">$1</span>',
                        $value['title']
                    );
                }
            });
        $this->success('success', $list);
    }

    /**
     * 获取他人主页
     * */
    public function actionGetOtherHome()
    {
        if (empty($this->params['user_id'])) {
            $this->error('缺少当前主页的用户ID');
        }
        try {
            $rows = UserInfo::instance()->get(['user_id' => $this->params['user_id']], ['userQualificationsHasMany', 'contentHasMany', 'userHasOne']);
            if (!$rows) {
                throw new Exception('未查询到当前用户主页信息');
            }
            $rows['is_contact'] = ($rows['is_rz'] != 2) ? false : true;
            $rows['is_mobile'] = empty($rows['mobile']) ? false : true;
            $rows['is_wechat'] = empty($rows['wechat_number']) ? false : true;
            $rows['is_rz'] = ($rows['is_rz'] != 2) ? false : true;
            // todo 人脉来源
            $rows['source'] = '公共人脉';
            $rows['is_yq'] = 0;
            $rows['is_rm'] = false;
            $condition['user_id'] = $this->params['user_id'];
            $condition['to_user_id'] = $this->auth->id;
            if (OfflineInformation::instance()->get(['user_id' => $this->auth->id, 'to_user_id' => $this->params['user_id']])) {
                $condition['user_id'] = $this->auth->id;
                $condition['to_user_id'] = $this->params['user_id'];
            }
            if ($offline = OfflineInformation::instance()->get($condition)) {
                if ($offline['state'] != 2) {
                    $rows['source'] = '公共人脉';
                } else {
                    $rows['source'] = '我的人脉';
                    $rows['is_rm'] = true;
                }
                $rows['is_yq'] = 2;
            }

            if ($message = Message::instance()->where(['user_id' => $this->auth->id ?? 0, 'to_user_id' => $this->params['user_id'], 'type' => ['in', [1, 2]]])->order('createtime desc')->find()) {
                $rows['source'] = '渠道人脉';
                $rows['is_rm'] = true;
                $rows['is_yq'] = $message['status'];
            }
            $price = 0;
            if ($offline_ = OfflineInformation::instance()->get(['to_user_id' => $this->params['user_id']])) {
                $price = floatval($offline_['price']);
                // 推荐人手机号
                $rows['recommendTel'] = UserInfo::instance()->where(['user_id' => $offline_['user_id']])->value('mobile');
            }
            $rows['price'] = empty($rows['price']) ? $price : $rows['price'];
            $rows = $rows->toArray();

            $rows['networkingList'] = OfflineInformation::instance()->field('id, username, sex, price, topic, industry')
                ->where(['user_id' => $this->auth->id ?? 0, 'state' => 2])
                ->select(); // 人脉
            $this->success('success', $rows);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取用户绑定的线下资料数据
     * */
    public function getOfflineInformation()
    {
        if (empty($this->params['to_user_id'])) {
            $this->error('缺少他人的用户ID');
        }

        $offLine = OfflineInformation::instance()->field('updatetime, createtime', true)
            ->where(['to_user_id' => $this->params['to_user_id'], 'user_id' => $this->auth->id])
            ->where(['pid' => ['<>', 0]])
            ->find();
        if (!$offLine) {
            $this->success('success', null);
        }
        $offLine = $offLine->toArray();
        $offLine['address'] = empty($offLine['address']) ? '' : explode(',', $offLine['address']);
        $offLine['is_rm'] = ($offLine['user_id'] == $this->auth->id ?? 0) ? true : false;
        $this->success('success', $offLine);
    }

    /**
     * 根据id获取人脉详情
     * */
    public function actionGetNetworkingDetail()
    {
        if (empty($this->params['id'])) {
            $this->error('缺少进入人脉详情的ID');
        }
        try {
            if (!$rows = OfflineInformation::instance()->get(['id' => $this->params['id']])) {
                throw new Exception('未查询到该人脉信息');
            }
            $this->success('success', $rows);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 对接企查查企业查询
     * */
    public function enterpriseQuery()
    {
        $param = $this->request->get();
        if (empty($param['search'])) {
            $this->error('搜索内容不能为空');
        }
        try {
            // 请求企业主体搜索
            $requestParam = [
                'searchKey' => $param['search'],
                'key' => config('site.key'),
                'pageIndex' => $this->page,
                'pageSize' => $this->pageSize
            ];
            $time = time();
            $header = [
                'Accept: application/json',
                'Token: ' . strtoupper(md5(config('site.key') . $time . config('site.secretKey'))),
                'Timespan:' . $time
            ];
            $request = http_query_url('https://api.qichacha.com/FuzzySearch/GetList', 'get', $requestParam, $header);
            if ($request['Status'] != 200) {
                throw new Exception('企查查查询异常【错误码：' . $request['Status'] . '】,【描述：' . $request['Message'] . '】');
            }
            $this->success('success', ['total_page' => $request['Paging'], 'list' => $request['Result']]);
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }

    /**
     * 查询免费曝光审核
     * */
    public function queryExamine()
    {
        if (empty($this->params['type'])) {
            $this->error('缺少查询类型');
        }
        $result = [];
        // 查询是否实名认证
        $userInfo = UserInfo::instance()->get(['user_id' => $this->auth->id ?? 0]);
        $result['isAuthentication'] = empty($userInfo) ? 1 : $userInfo['is_rz'];
        // 查询信息审核
        $showExamine = ShowExamine::instance()->where(['user_id' => $this->auth->id ?? 0, 'type' => $this->params['type']])->order('createtime DESC')->find();
        $result['examineStatus'] = empty($showExamine) ? 1 : $showExamine['status'];
        $result['examineNote'] = empty($showExamine) ? '' : $showExamine['note'];
        $this->success('success', $result);
    }

    /**
     * 免费人脉申请
     * @throws
     * */
    public function connectionsApply()
    {
        if (empty($this->params['is_unit'])) {
            $this->error('请选您是否有无单位的选项');
        }

        if ($this->params['is_unit'] == 2) {
            if (empty($this->params['unit_name'])) {
                $this->error('请输入您的单位名称');
            }
        }
        if (empty($this->params['to_user_id'])) {
            $this->error('缺少被申请人的ID');
        }
        $this->params['unit_name'] = ($this->params['is_unit'] == 2) ? $this->params['unit_name'] : '';
        if (!$toUser = \app\common\model\User::instance()->get(['id' => $this->params['to_user_id']])) {
            $this->error('被申请的用户不存在');
        }
        if (!$userInfo = UserInfo::instance()->get(['user_id' => $this->auth->id ?? 0])) {
            $this->error('请您先进行实名认证并完善个人资料后申请');
        }
        $userMemberOrder = UserCardOrders::instance()
            ->where(['user_id' => $this->auth->id ?? 0, 'status' => 2, 'expire_date' => ['>=', date('Y-m-d H:i:s')]])
            ->order('pay_time DESC')
            ->find();
        // todo 判断申请者是否是会员
        if ($userMemberOrder) {
            $this->error('您是会员用户，无法走免费申请通道');
        }
        $toUserMemberOrder = UserCardOrders::instance()
            ->where(['user_id' => $this->params['to_user_id'] ?? 0, 'status' => 2, 'expire_date' => ['>=', date('Y-m-d H:i:s')]])
            ->order('pay_time DESC')
            ->find();
        if ($toUserMemberOrder) {
            $orderParams = json_decode($toUserMemberOrder['params'], true);
            $messageNumber = Message::instance()->where(['to_user_id' => $this->params['to_user_id'] ?? 0, 'type' => 1, 'status' => 2])->count(1);
            // todo 统计申请次数是否足够
            if ($messageNumber >= $orderParams['look_number']) {
                $this->error('您的可查看次数不足');
            }
        }
        // todo 避免已申请查看待同意的用户无限申请
        if ($message = Message::instance()->where(['user_id' => $this->auth->id ?? 0, 'to_user_id' => $this->params['to_user_id'], 'type' => 1, 'status' => 1])->order('createtime desc')->find()) {
            $this->error('请勿重复申请');
        }
        $desc = '公共人脉';
        if ($offline = OfflineInformation::instance()->get(['user_id' => $this->params['to_user_id'], 'to_user_id' => $this->auth->id ?? 0])) {
            if ($offline['state'] != 2) {
                /** @var TYPE_NAME $desc */
                $desc = '公共人脉';
            }
            if ($offline['state'] == 2) {
                $this->error('您们已是人脉绑定关系,可直接查询');
            }
        }
        if (Message::instance()->where(['user_id' => $this->auth->id ?? 0, 'to_user_id' => $this->params['to_user_id'], 'type' => ['in', [1, 2]]])->order('createtime desc')->find()) {
            $desc = '渠道人脉';
        }
        $user_name = $userInfo['nickname'];
        if (!empty($this->params['pid'])) {
            if (!OfflineInformation::instance()->get(['id' => $this->params['pid']])) {
                $this->error('线下资料不存在');
            }
        }
        Db::startTrans();
        try {
            $this->params['user_id'] = $this->auth->id ?? 0;
            if ($result = Enterprise::instance()->allowField(true)->save(array_filter($this->params))) {
                // todo 把申请写入到消息表当中
                Message::instance()->allowField(true)->save([
                    'user_id' => $this->auth->id ?? 0,
                    'to_user_id' => $this->params['to_user_id'],
                    'pid' => $this->params['pid'] ?? 0,
                    'content' => json_encode(array(
                        'fullName' => $userInfo['nickname'],
                        'hiddenFullName' => mb_substr($user_name, 0, 1, 'utf-8') . str_repeat("*", (strlen($user_name) / 2 - 1)),
                        'city' => implode('', $userInfo['city']),
                        'desc' => $desc,
                        'status' => $userInfo['status'],
                        'statusDesc' => ($userInfo['status'] == 1) ? '曝光中' : '未曝光',
                        'is_rz' => $userInfo['is_rz'],
                        'is_mobile_rz' => empty($userInfo['mobile']) ? '手机未认证' : '手机已认证',
                        'industry' => $userInfo['industry'],
                        'createtime' => date('Y-m-d H:i') . '向您发起名片查看'
                    ), JSON_UNESCAPED_UNICODE),
                    'type' => 1
                ]);
                Db::commit();
                $this->success('success');
            }
            throw new Exception('申请失败,请重新尝试');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取我的消息列表
     * @throws
     * */
    public function getMessageList()
    {
        if (empty($this->params['type'])) {
            $this->error('缺少获取消息类型');
        }
        $condition = [];
        if ($this->params['type'] == 1) { // 申请消息
            $condition['status'] = 1;
            $condition['to_user_id'] = $this->auth->id ?? 0;
        } else { // 通知消息
            $condition['status'] = ['in', [2, 3]];
            $condition['user_id'] = $this->auth->id ?? 0;
        }
        $list = Message::instance()
            ->field('updatetime', true)
            ->where($condition)
            ->order('createtime desc')
            ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) {
                if (in_array($value['status'], [2, 3])) {
                    unset($value['content']);
                    $user = UserInfo::get(['user_id' => $value['to_user_id']]);
                    if (!empty($user)) {
                        $value['content'] = json_encode(array(
                            'fullName' => $user['nickname'],
                            'hiddenFullName' => mb_substr($user['nickname'], 0, 1, 'utf-8') . str_repeat("*", (strlen($user['nickname']) / 2 - 1))
                        ), JSON_UNESCAPED_UNICODE);
                    }
                }
            });
        $this->success('success', $list);
    }

    /**
     * 消息列表同意和拒绝操作
     * @throws
     * */
    public function apply()
    {
        $offlineInformation = new OfflineInformation();
        if (empty($this->params['type'])) {
            $this->error('缺少查看类型');
        }
        if ($this->params['type'] == 2) {
            if (empty($this->params['id'])) {
                $this->error('缺少消息ID');
            }
        }
        if (empty($this->params['to_user_id'])) {
            $this->error('缺少被申请的用户ID');
        }
        if (empty($this->params['status'])) {
            $this->error('缺少操作状态');
        }
        // todo 检查同意者是否属于会员
        $toUserMemberOrder = UserCardOrders::instance()
            ->where(['user_id' => $this->auth->id ?? 0, 'status' => 2, 'expire_date' => ['>=', date('Y-m-d H:i:s')]])
            ->order('pay_time DESC')
            ->find();
        if (!$toUserMemberOrder && $this->params['status'] == 2) {
            $this->error('您不是会员,请先充值会员后操作');
        }
        Db::startTrans();
        try {
            if ($this->params['type'] == 2) {
                if (!$message = Message::instance()->get(['id' => $this->params['id'], 'to_user_id' => $this->auth->id ?? 0])) {
                    throw new Exception('您没有此消息的操作权限');
                }
                if (in_array($message['status'], [2, 3])) {
                    throw new Exception('此内容已被您操作过了');
                }
            }
            if ($this->params['type'] == 1) { // todo 是会员的用户可直接进行查看，所以要直接添加消息到数据库并把状态直接改成同意
                $result = Message::instance()->allowField(true)->save([
                    'user_id' => $this->auth->id ?? 0,
                    'to_user_id' => $this->params['to_user_id'],
                    'pid' => $this->params['pid'] ?? 0,
                    'type' => 1,
                    'status' => 2
                ]);
            } else { // todo 如果是他人非会员用户申请的话，那么被申请人则需要操作同意或者拒绝按钮修改已记录消息的状态
                $result = $message->allowField(true)->save(['status' => $this->params['status']]);
            }
            $userId = $this->auth->id ?? 0; // todo 操作者ID
            $toUserId = $this->params['to_user_id']; // todo 申请人ID
            $pid = [];
            if (!empty($this->params['pid'])) {
                $pid['pid'] = $this->params['pid'];
            }
            // todo 避免重复绑定
            $bind = $offlineInformation
                ->where(['state' => 2])
                ->where(['user_id' => $userId, 'to_user_id' => $toUserId])
                ->where($pid)
                ->count(1);
            $toBind = $offlineInformation
                ->where(['state' => 2])
                ->where(['user_id' => $toUserId, 'to_user_id' => $userId])
                ->where($pid)
                ->count(1);
            if ($bind && $toBind) {
                throw new Exception('您们已是绑定关系');
            }
            if ($result && $this->params['status'] == 2) {
                // todo 绑定人脉
                if (!$userInfo = UserInfo::instance()->get(['user_id' => $toUserId])) {
                    $this->error('需要绑定的用户不存在');
                }
                // todo 绑定申请用户
                if ($userInfo) {
                    $field = array_intersect($offlineInformation->getTableFields(), $userInfo->getTableFields());
                    $newField = [];
                    foreach ($field as $fieldValue) {
                        $newField[$fieldValue] = $userInfo[$fieldValue];
                    }
                    $field = $offlineInformation::instance()->_initialize($newField)->delField('id, status, user_id, createtime, updatetime');
                    $field['username'] = $userInfo['name'];
                    $field['wxh'] = $userInfo['wechat_number'];
                    $field['address'] = $userInfo['city'];
                }
                $field['user_id'] = $this->auth->id ?? 0; // 绑定者
                $field['to_user_id'] = $toUserId; // 被绑定者
                $field['state'] = 2;
                $field['type'] = 1;
                $field['content_type'] = 1;
                if (!empty($this->params['pid'])) {
                    $field['pid'] = $this->params['pid'];
                    $field['type'] = 2;
                    $field['content_type'] = 2;
                }
                // todo 申请用户绑定操作同意的用户
                if ($toUserInfo = UserInfo::instance()->get(['user_id' => $this->auth->id ?? 0])) {
                    $toField = array_intersect($offlineInformation->getTableFields(), $toUserInfo->getTableFields());
                    $toNewField = [];
                    foreach ($toField as $toFieldValue) {
                        $toNewField[$toFieldValue] = $toUserInfo[$toFieldValue];
                    }
                    $toField = $offlineInformation::instance()->_initialize($toNewField)->delField('id, status, user_id, createtime, updatetime');
                    $toField['username'] = $toUserInfo['nickname'] ?? '';
                    $toField['wxh'] = $toUserInfo['wechat_number'] ?? '';
                    $toField['address'] = $toUserInfo['city'] ?? '';
                }
                $toField['user_id'] = $this->params['to_user_id'];
                $toField['to_user_id'] = $this->auth->id ?? 0;
                $toField['state'] = 2;
                $toField['type'] = 1;
                $toField['content_type'] = 1;
                if (!empty($this->params['pid'])) {
                    $toField['pid'] = $this->params['pid'];
                    $toField['type'] = 2;
                    $toField['content_type'] = 2;
                }
                $offlineInformation::instance()->allowField(true)->saveAll(array_merge([$field], [$toField]));
            }
            Db::commit();
            $this->success('success');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 实名认证
     * @throws
     * */
    public function realNameAuthentication()
    {
        if (empty($this->params['name'])) {
            $this->error('缺少用户姓名');
        }
        if (empty($this->params['id_cards'])) {
            $this->error('缺少用户身份证号码');
        }
        $model = UserInfo::instance();
        if ($userInfo = UserInfo::instance()->get(['user_id' => $this->auth->id ?? 0])) {
            $model = $userInfo;
            if ($userInfo['is_rz'] == 2) {
                $this->error('您已进行了认证，无需重复认证');
            }
        }
        $this->params['user_id'] = $this->auth->id ?? 0;
        $this->params['is_rz'] = ($this->params['is_rz'] == 1) ? 2 : 3;
        Db::startTrans();
        try {
            $result = $model->allowField(true)->save($this->params);
            if ($result) {
                Db::commit();
                $this->success('success');
            }
            throw new Exception('实名认证失败');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 购买会员的明细
     * @throws
     * */
    public function payMemberOrderDetail()
    {
        $list = UserCardOrders::instance()
            ->field('id, user_id, order_sn, DATE_FORMAT(expire_date, "%Y-%m-%d") as expire_date, params, money')
            ->where(['user_id' => $this->auth->id ?? 0])
            ->order('createtime DESC')
            ->paginate($this->pageSize, false, ['page' => $this->page])->each(function (&$value) {
                $params = json_decode($value['params'], true);
                $value['name'] = $params['name'];
                $value['month'] = $params['month'] . '个月';
                unset($value['params']);
            });
        $this->success('success', $list);
    }

    /**
     * 我的老师-权限修改公开不公开
     * @throws
     * */
    public function updateTeacherStatus()
    {
        if (empty($this->params['status'])) {
            $this->error('请选择是否公开');
        }

        if (empty($this->params['ids'])) {
            $this->error('缺少要修改的数据ID');
        }
        $status = $this->params['status'];
        $offline = collection(OfflineInformation::instance()->where(['id' => ['in', array_unique(explode(',', $this->params['ids']))], 'user_id' => $this->auth->id ?? 0])->select())->toArray();
        if (!$offline) {
            $this->error('您需要公开的师资数据不存在');
        }
        $oldArray = [];
        foreach ($offline as $offlineKey => $offlineValue) {
            $oldArray[$offlineKey]['id'] = $offlineValue['id'];
            $oldArray[$offlineKey]['status'] = $offlineValue['status'];
        }
        $ids = array_column($offline, 'id');
        $array = [];
        foreach ($ids as $key => $value) {
            $array[$key]['id'] = $value;
            $array[$key]['status'] = $status;
        }
        Db::startTrans();
        try {
            // $result = OfflineInformation::instance()->allowField(true)->saveAll($array, true)
            if ($result = ShowExamine::instance()->allowField(true)->save(['user_id' => $this->auth->id ?? 0, 'type' => 3, 'orign_data' => json_encode($oldArray, JSON_UNESCAPED_UNICODE), 'new_date' => json_encode($array, JSON_UNESCAPED_UNICODE)])) {
                Db::commit();
                $this->success('操作成功,请耐心等待审核');
            }
            throw new Exception('操作失败');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }

    /**
     * 根据线下资料ID获取线下资料详情
     * */
    public function getInformationDetail()
    {
        if (empty($this->params['id'])) {
            $this->error('缺少线下资料的ID');
        }
        $rows = OfflineInformation::instance()->get(['id' => $this->params['id'], 'content_type' => 2]);
        // todo 获取线下资料的资质
        $rows['qualifications'] = InformationQualifications::instance()->where(['oid' => $rows['id']])->select();
        $this->success('success', $rows);
    }

    /**
     * 一键同步名片
     * */
    public function synchronous()
    {

    }
}